﻿/*
    <div class='ChatRoomMember floatLeft' id='m_sip'>
                            <div class='floatLeft'>
                                <span class='ms-spimn-presenceWrapper ms-spimn-imgSize-8x72'>
                                    <img src='~site/_layouts/spimn.png' class='ms-spimn-img ms-spimn-presence-online-8x72x32 ChatRoomMemberStatusImage' />
                                </span>
                                <img src='~site/_layouts/PersonPlaceholder.png' class='ChatRoomMemberPhoto' />
                            </div>
                            <div class='floatLeft'>
                                <div class='MemberNameAndTitle'><span class='MemberName'>程呈</span><span class='memberSplit'> - </span><span class='MemberTitle'>高级项目经</span></div>
                                <div class='MemberDepartment'>系统管理科</div>
                                <div class='MemberAdmin'>管理员</div>
                            </div>
                            <div class='clearLeft'></div>
                        </div>
*/

/*
  <div class='floatLeft samllAdmin' id='a_sip'>
                            <div class='ms-spimn-presenceWrapper-Small  ms-spimn-imgSize-16x16 samllAdminIndicator floatLeft'>
                                <img name='imnmark' title='test' class='ms-spimn-img ms-spimn-presence-online-16x16x32 adminIndicatorImage' alt='No presence information' src='~site/_layouts/spimn.png' />
                            </div><div class='adminTitle floatLeft'>程呈</div>
                              <div class='clearLeft'></div>
                        </div>
 */

currentRoomItem = null;
var lyncUsers = [];
// Golbal var currentRoomInfo;
var userIds;
var sips;
var isAdmin;
var currentUser;
loadedCurrentUser = false;
loadedChatRoomInfo = false;
loadDataComplete = false;
var editChatRoomUrl = "/Lists/chatrooms/EditForm.aspx?ID={0}&Source={1}";

function ChatRoomInfo(meetingRoomUrl, chatRoomSecurityGroupAdmin, chatRoomSecurityGroupMember, chatDescription, chatRoomAdmins, chatRoomMembers, roomName, sIP, id, chatRoomId) {
    this.meetingRoomUrl = meetingRoomUrl;
    this.chatRoomSecurityGroupAdmin = chatRoomSecurityGroupAdmin;
    this.chatRoomSecurityGroupMember = chatRoomSecurityGroupMember;
    this.chatDescription = chatDescription;
    this.chatRoomAdmins = chatRoomAdmins;
    this.chatRoomMembers = chatRoomMembers;
    this.roomName = roomName;
    this.sIP = sIP;
    this.id = id;
    this.chatRoomId = chatRoomId;
}

function LyncUser(id, title, department, jobTitle, picture, role) {
    // alert(user.get_item("ID") + "," + user.get_item("Title") + "," + user.get_item("Department") + "," + user.get_item("JobTitle") + "," + picture);
    this.id = id;
    this.title = title;
    this.department = department;
    this.jobTitle = jobTitle;
    this.picture = picture;
    this.role = role;    
}

function GetLyncUserById(id) {
    if (lyncUsers && lyncUsers.length > 0) {
        for (var i = 0; i < lyncUsers.length; i++) {
            if (lyncUsers[i].id == id) {
                return lyncUsers[i];
            }
        }
    }

    return null;
}

function RenderData() {
    // Render the chat room information
    // Update the chat room title
    var chatRoomHomeTitle = document.getElementById("ChatRoomHomeTitleContent");
    chatRoomHomeTitle.innerText = currentRoomInfo.roomName;

    // Update the ChatRoomTitle
    var chatRoomTitle = document.getElementById("ChatRoomTitle");
    chatRoomTitle.innerText = currentRoomInfo.roomName;

    // Update the ChatRoomDescription
    var chatRoomDescription = document.getElementById("ChatRoomDescription");
    if (fucCheckLength(currentRoomInfo.chatDescription) > 88) {
        chatRoomDescription.setAttribute("title", currentRoomInfo.chatDescription);
        // chatRoomDescription.title = currentRoomInfo.chatDescription;
    }
    chatRoomDescription.innerText = currentRoomInfo.chatDescription;


    // Update the memberAvaiableLable
    UpdateMemberAvaiableLable();

    RenderAdmins();
    RenderMemebers();

    // ChatRoomInfoInnerTabContent
    var chatRoomBusy = document.getElementById("ChatRoomBusy");
    chatRoomBusy.classList.add("hidden");
    var chatRoomInfoInnerTabContent = document.getElementById("ChatRoomInfoInnerTabContent");
    chatRoomInfoInnerTabContent.classList.remove("hidden");
}

function UpdateMemberAvaiableLable() {
    var totalUserCount = sips.length;
    var avaiableCount = 0;
    for (var index =0; index < sips.length; index++) {
        var statusCode = slCtl.Content.SL2JS.GetContactStatus(sips[index]);
        if (statusCode && (statusCode == "3500" || statusCode == "5000" || statusCode == "6500" || statusCode == "6500" || statusCode == "7500" || statusCode == "9500")) {
            avaiableCount++;
        }
    }

    var memberAvaiableLable = document.getElementById("memberAvaiableLable");
    memberAvaiableLable.innerText = avaiableCount + "/" + totalUserCount;
}

function RenderAdmins() {  
    var chatRoomAdminContainer = document.getElementById("ChatRoomAdminContainer");
    var chatRoomMembers = document.getElementById("ChatRoomMembers");
    if (lyncUsers && lyncUsers.length > 0) {
        for (var i = 0; i < lyncUsers.length; i++) {
        var currentSIP = sips[userIds.indexOf(lyncUsers[i].id)];
        var statusCode = slCtl.Content.SL2JS.GetContactStatus(currentSIP);
        if (lyncUsers[i].role == "管理员") {
            var adminDiv = document.createElement("div");
            adminDiv.className = "floatLeft samllAdmin";
            adminDiv.id = "a_" + sips[userIds.indexOf(lyncUsers[i].id)];
            var className = GetStatusClass(statusCode, true);
            var innerHtml = GetChatAdminInnerHtml(sips[userIds.indexOf(lyncUsers[i].id)], lyncUsers[i].title, className);
            adminDiv.innerHTML = innerHtml;
            chatRoomAdminContainer.insertBefore(adminDiv, chatRoomAdminContainer.lastChild);
        }
       
        var mdiv = document.createElement("div");
        mdiv.className = "ChatRoomMember floatLeft";
        mdiv.id = "m_" + sips[userIds.indexOf(lyncUsers[i].id)];
        var className = GetStatusClass(statusCode, true);
        var innerHtml = GetChatMemeberInnerHtml(sips[userIds.indexOf(lyncUsers[i].id)], lyncUsers[i].title, lyncUsers[i].jobTitle, lyncUsers[i].department, lyncUsers[i].role, lyncUsers[i].picture, className);
        mdiv.innerHTML = innerHtml;
        chatRoomMembers.insertBefore(mdiv, chatRoomMembers.lastChild);
        
      }
    }
}

function RenderMemebers() {
    // 

}

function ChatRoonTabLoad() {
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", QueryChatRoom);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", QueryCurrentUser);
}

function QueryChatRoom() {
    var clientContext = new SP.ClientContext();
    roomId = clientContext.$1P_0.substring(1);
    var chatRoomList = clientContext.get_site().get_rootWeb().get_lists().getByTitle('群组');
    var query = "  <View><Query>" +
                                         "<Where>" +
                                              "<Eq>" +
                                                "<FieldRef Name='ChatRoomID' />" +
                                                "<Value Type='Text'>" + roomId + "</Value>" +
                                              "</Eq>" +
                                            "</Where>" +
                                    "</Query></View>";

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(query);
    currentRoomItem = chatRoomList.getItems(camlQuery);

    clientContext.load(currentRoomItem, 'Include(MeetingRoomUrl,ChatRoomSecurityGroupAdmin,ChatRoomSecurityGroupMember,ChatDescription,ChatRoomAdmins,ChatRoomMembers,RoomName,SIP,ID,ChatRoomID)');

    clientContext.executeQueryAsync(QueryChatRoomSuccessed, onQueryFailed);
}

function QueryCurrentUser() {
    context = new SP.ClientContext.get_current();

    web = context.get_web();

    currentUser = web.get_currentUser();

    context.load(currentUser);

    context.executeQueryAsync(OnQueryCurrentUserSuccessed, onQueryFailed);
}

var userItems;
function QueryUsers(userIds) {
    context = new SP.ClientContext.get_current();
    web = context.get_web();
    var userInfoList = web.get_siteUserInfoList();
    var camlQuery = new SP.CamlQuery();
    var values = "";
    for (var index = 0; index < userIds.length; index++) {
        values += '<Value Type=\'Number\'>' + userIds[index] + '</Value>';
    }
    camlQuery.set_viewXml('<View><Query><Where><In><FieldRef Name=\'ID\'/>' + '<Values>' + values + '</Values></In>' + '</Where></Query></View>');
    userItems = userInfoList.getItems(camlQuery);

    context.load(userItems, 'Include(ID,Title,Department,JobTitle,Picture)');
    context.executeQueryAsync(OnQuerUsersSuccessed, onQueryFailed);
}

function OnQuerUsersSuccessed() {
    var usersEnumerator = userItems.getEnumerator();
    while (usersEnumerator.moveNext())
    {
        var user = usersEnumerator.get_current();
        var picture = GetSiteUrl() + "/_layouts/PersonPlaceholder.png"
        if (user.get_item("Picture")) {
            picture = user.get_item("Picture").get_url();
        }
        // alert(user.get_item("ID") + "," + user.get_item("Title") + "," + user.get_item("Department") + "," + user.get_item("JobTitle") + "," + picture);
       
        var role = "";
        for (var index = 0; index < currentRoomInfo.chatRoomAdmins.length; index++) {
            var userId = user.get_item("ID");
            var currentAdmin = currentRoomInfo.chatRoomAdmins[index];
            var adminId = currentAdmin.get_lookupId();
            if (userId == adminId) {
                role = "管理员";
            }
        }

        var lyncUser = new LyncUser(user.get_item("ID"), user.get_item("Title"), user.get_item("Department"), user.get_item("JobTitle"), picture, role);
        lyncUsers.push(lyncUser);
    }
    
    if(slCtl)
    {
        RenderData();
    }

    loadDataComplete = true;
}

function GetSiteUrl() {
    var port = "";
    if (document.location.port && document.location.port.lenght >0) {
        port = ":" + document.location.port;
    }

    return document.location.protocol + '//' + document.location.host + port;
}
function OnQueryCurrentUserSuccessed() {
    loadedCurrentUser = true;
    if (loadedChatRoomInfo) { 
        CheckIfAdmin();
    }
    // alert(currentUser.get_id());
    // currentUser.get_id() 1
    // currentUser.get_title()  程成
    globalConfig.currentUserId = currentUser.get_id();
    globalConfig.currentUserName = currentUser.get_title();
    // get_loginName()
    var loginName = currentUser.get_loginName();
    if (loginName) {
        var tempLoaginName = loginName.split("|");
        if (tempLoaginName.length == 2) {
            loginName = loginName.split("|")[1];
        }
    }

    globalConfig.currentUserLoginName = loginName;
}

function CheckIfAdmin() {
    var currentUserId = currentUser.get_id();
    for (var index = 0; index < currentRoomInfo.chatRoomAdmins.length; index++) {
        var currentAdmin = currentRoomInfo.chatRoomAdmins[index];
        var currentAdminId = currentAdmin.get_lookupId();
        if (currentUserId == currentAdminId) {
            isAdmin = true;
            globalConfig.isAdmin = true;
            //var startMeeting = document.getElementById("StartMeeting");
            // startMeeting.classList.remove("hidden");

            var editChatRoom = document.getElementById("EditChatRoom");
            editChatRoom.classList.remove("hidden");

            var chatRoomHomeTitle = document.getElementById("ChatRoomHomeTitle");
            // chatRoomHomeTitle.classList.add("ChatRoomHomeTitleLong");

            var publishMeetingRecord = document.getElementById("PublishMeetingRecord");
            publishMeetingRecord.classList.remove("hidden");
            var manageFolderStructure = document.getElementById("ManageFolderStructure");
            manageFolderStructure.classList.remove("hidden");
            break;
        }
    }
}

function QueryChatRoomSuccessed() {
    var chatRoomEnumerator = currentRoomItem.getEnumerator();
    while (chatRoomEnumerator.moveNext()) {
        var chatroom = chatRoomEnumerator.get_current();
        var meetingRoomUrl = chatroom.get_item("MeetingRoomUrl");       
        var chatRoomSecurityGroupAdmin = chatroom.get_item("ChatRoomSecurityGroupAdmin");
        var chatRoomSecurityGroupMember = chatroom.get_item("ChatRoomSecurityGroupMember");
        var chatDescription = chatroom.get_item("ChatDescription");
        var chatRoomAdmins = chatroom.get_item("ChatRoomAdmins");
        // alert("chatRoomAdmins:" + chatRoomAdmins)
        var chatRoomMembers = chatroom.get_item("ChatRoomMembers");
        // alert("chatRoomMembers:" + chatRoomMembers);
        var roomName = chatroom.get_item("RoomName");
        var roomSIP = chatroom.get_item("SIP");
        var roomItemId = chatroom.get_item("ID");
        var chatRoomID = chatroom.get_item("ChatRoomID");
        // chatRoomAdmins[0].get_lookupValue()
        // chatRoomAdmins[0].get_lookupId()
        userIds = [];
        sips = [];       
        var roomSips = roomSIP.split(";");
        var usersSips = "";
        setTimeout(function () { CheckWindowsUserMatchLyncUser(roomSips); }, 1000);
        for(var i=0; i<roomSips.length-1; i++)
        {
            var currentSIP = roomSips[i].split("#");            
            userIds.push(currentSIP[0]);
            sips.push(currentSIP[1]);
            usersSips += currentSIP[1] + "#";
        }

        QueryUsers(userIds);
        currentRoomInfo = new ChatRoomInfo(meetingRoomUrl, chatRoomSecurityGroupAdmin, chatRoomSecurityGroupMember, chatDescription, chatRoomAdmins, chatRoomMembers, roomName, usersSips, roomItemId, chatRoomID);
        loadedChatRoomInfo = true;
        if (loadedCurrentUser) {
            CheckIfAdmin();
        }

        editChatRoomUrl = GetSiteUrl() + "/Lists/chatrooms/EditForm.aspx?ID=" + roomItemId + "&Source=" + document.location.href;
        var editChatRoom = document.getElementById("EditChatRoom");
        editChatRoom.onclick = function () {
            // document.location = editChatRoomUrl;
            ShowEditMeetingRoomDialog(editChatRoomUrl)
        }

        if (slCtl) {
            slCtl.Content.SL2JS.SetLyncUsers(usersSips);
            slCtl.Content.SL2JS.SetMeetingUrl(meetingRoomUrl);

            // SetMeetingId
            slCtl.Content.SL2JS.SetMeetingId(chatRoomID);
            slCtl.Content.SL2JS.SetWebUrl(GetSiteUrl());          
        }       
    }
}

function ShowEditMeetingRoomDialog(url) {   
        var options = {
            url: url,
            width: 600,
            height: 260,
            title: "编辑群组",
            dialogReturnValueCallback: CallBackfromEditMeetingRoomDialog
        };
        SP.UI.ModalDialog.showModalDialog(options);    
}

function CallBackfromEditMeetingRoomDialog(dialogResult)
{
    if (dialogResult == 1) {
        // refresh current page
        document.location.reload();
    }
    else {
        // Do nothing
    }
}
    function CheckWindowsUserMatchLyncUser(roomSips) {
        for (var i = 0; i < roomSips.length - 1; i++) {
            var currentSIP = roomSips[i].split("#");
            if (globalConfig.currentUserId == currentSIP[0]) {
                globalConfig.currentSIP = currentSIP[1];
            }
        }

        var lyncSIP = slCtl.Content.SL2JS.GetCurrentSIP();
        if (globalConfig.currentSIP && (globalConfig.currentSIP.toLowerCase() == lyncSIP.toLowerCase())) {
            // window user matched the lync user, do nothing
        }
        else if (globalConfig.currentUserLoginName && lyncSIP) {
            
            SetErrorMessage("windows 登陆帐号" + globalConfig.currentUserLoginName + "与lync 登陆帐号" + lyncSIP + " 不一致");
        }
    }

    function SetErrorMessage(errorMessage)
    {
        var errorDiv = document.getElementById("ErrorDiv");
        var errorMessageDiv = document.getElementById("ErrorMessageDiv");
        errorMessageDiv.innerHTML = errorMessage;
        errorDiv.classList.remove("hidden");

        var chatRoomHome = document.getElementById("ChatRoomHome");
        chatRoomHome.classList.add("hidden");
    }

    function onQueryFailed(sender, args) {
        alert('error' + args.message);
    }

    _spBodyOnLoadFunctionNames.push("ChatRoonTabLoad");
    function GetChatAdminInnerHtml(sip, name, className) {
        return "<div class='ms-spimn-presenceWrapper-Small  ms-spimn-imgSize-16x16 samllAdminIndicator floatLeft'>" +
                                "<img name='imnmark'  class='ms-spimn-img " + className + " adminIndicatorImage' alt='No presence information' src='~site/_layouts/spimn.png' />" +
                                " </div><div class='adminTitle floatLeft'>"+name+"</div>" +
                                "<div class='clearLeft'></div>";
    }

    function GetChatMemeberInnerHtml(sip, name, title, department, role, photo, className) {
        var delta = 0;
        if (name.length >= 3) {
            delta = 1;
        }

        if (!title) {
            title = "";
        }
        else if (title && title.length > 5 - delta) {
            title = title.substring(0, 5 - delta);
        }

        if (!department) {
            department = "";
        }
        else if (department && department.length > 6) {
            department = department.substring(0, 7);
        }



//        return "<div class='floatLeft'>" +
//                                    "<span class='ms-spimn-presenceWrapper ms-spimn-imgSize-8x72'>" +
//                                        "<img src='~site/_layouts/spimn.png' class='ms-spimn-img "+className+" ChatRoomMemberStatusImage' />" +
//                                    "</span>" +
//                                    "<img src='"+photo+"' class='ChatRoomMemberPhoto' />" +
//                                "</div>" +
//                                "<div class='floatLeft'>" +
//                                    "<div class='MemberNameAndTitle'><span class='MemberName'>" + name + "</span><span class='memberSplit'> - </span><span class='MemberTitle'>"+title+"</span></div>" +
//                                    " <div class='MemberDepartment'>" + department + "</div>" +
//                                    "<div class='MemberAdmin'>"+role+"</div>" +
//                                "</div>" +
        //                                "<div class='clearLeft'></div>";

        return "<div class='ms-spimn-presenceWrapper-Small  ms-spimn-imgSize-16x16 samllAdminIndicator floatLeft'>" +
            " <img name='imnmark' class='ms-spimn-img " + className + " adminIndicatorImage' alt='No presence information' src='~site/_layouts/spimn.png' />" +
              "</div> <div class='adminTitle floatLeft'>" + name + "</div>   <div class='clearLeft'></div></div>"
    }

    /*
    <div class='floatLeft samllAdmin' id='a_sip'>
    <div class='ms-spimn-presenceWrapper-Small  ms-spimn-imgSize-16x16 samllAdminIndicator floatLeft'>
    <img name='imnmark' title='test' class='ms-spimn-img ms-spimn-presence-online-16x16x32 adminIndicatorImage' alt='No presence information' src='~site/_layouts/spimn.png' />
    </div><div class='adminTitle floatLeft'>程呈</div>
    <div class='clearLeft'></div>
    </div>
    */
